package org.jeecg.modules.mybatis;

import com.google.common.base.CaseFormat;
import com.transtella.messageCenter.IMessageManager;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.binding.MapperMethod;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.plugin.*;
import org.jeecg.common.config.TenantContext;
import org.jeecg.common.constant.TenantConstant;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.config.mybatis.MybatisPlusSaasConfig;
import org.jeecg.modules.utils.entity.WmsBaseDocument;
import org.jeecg.modules.utils.mapper.WmsBaseDocumentMapper;
import org.jeecg.modules.utils.service.IWmsBaseDocumentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;
import java.util.*;

/**
 * mybatis拦截器，自动注入创建人、创建时间、修改人、修改时间
 *
 * @Author scott
 * @Date 2019-01-19
 */
@Slf4j
@Component
@Intercepts({@Signature(type = Executor.class, method = "update", args = {MappedStatement.class, Object.class})})
public class MybatisMessageCenterInterceptor implements Interceptor {

    
    @Autowired
    private JdbcTemplate jdbcTemplate;

    public static final List<String> MESSAGE_TABLE = new ArrayList<String>();

    static {
        //1.需要自动发送消息的表请在此配置
        if (MybatisPlusSaasConfig.OPEN_SYSTEM_TENANT_CONTROL) {
            MESSAGE_TABLE.add("wms_in_receipt_task");
        }

    }

    @Override
    public Object intercept(Invocation invocation) throws Throwable {
        MappedStatement mappedStatement = (MappedStatement) invocation.getArgs()[0];
        String sqlId = mappedStatement.getId();
        log.debug("------sqlId------" + sqlId);
        SqlCommandType sqlCommandType = mappedStatement.getSqlCommandType();
        Object parameter = invocation.getArgs()[1];
        log.debug("------sqlCommandType------" + sqlCommandType);

        if (parameter == null) {
            return invocation.proceed();
        }

//        if (SqlCommandType.UPDATE == sqlCommandType) {
//            Field[] fields = null;
//            if (parameter instanceof MapperMethod.ParamMap) {
//                MapperMethod.ParamMap<?> p = (MapperMethod.ParamMap<?>) parameter;
//                //update-begin-author:scott date:20190729 for:批量更新报错issues/IZA3Q--
//                String et = "et";
//                if (p.containsKey(et)) {
//                    parameter = p.get(et);
//                } else {
//                    parameter = p.get("param1");
//                }
//                //update-end-author:scott date:20190729 for:批量更新报错issues/IZA3Q-
//
//                //update-begin-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
//                if (parameter == null) {
//                    return invocation.proceed();
//                }
//                //update-end-author:scott date:20190729 for:更新指定字段时报错 issues/#516-
//
//                fields = oConvertUtils.getAllFields(parameter);
//            } else {
//                fields = oConvertUtils.getAllFields(parameter);
//            }
//
//            String tableName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, parameter.getClass().getSimpleName());
//            if (MESSAGE_TABLE.indexOf(tableName) >= 0) {
//                for (Field field : fields) {
//                    log.debug("------field.name------" + field.getName());
//                    try {
//                        if ("documentStatus".equals(field.getName())) {
//                            //获取登录用户信息
//                            field.setAccessible(true);
//                            Object documentType = field.get(parameter);
//                            if (documentType.equals("2") || documentType.equals(2)) {
////                                messageManager.sendCommand("commit." + tableName, parameter);
//                            }
//                            field.setAccessible(false);
//                        }
//                    } catch (Exception e) {
//                        e.printStackTrace();
//                    }
//                }
//            }
//        }
        Object proceed = invocation.proceed();
        if (SqlCommandType.INSERT == sqlCommandType) {
            Field[] fields = oConvertUtils.getAllFields(parameter);
            // 有documentStatus这个字段的表,就认为是单据表,要保存
            for (Field field : fields) {
                if ("documentStatus".equals(field.getName())) {
                    String tableName = CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, parameter.getClass().getSimpleName());
                    WmsBaseDocument model = new WmsBaseDocument();
                    model.setTableName(tableName);

                    // 把documentStatus设置为1
                    field.setAccessible(true);
                    field.set(parameter,"1");
                    field.setAccessible(false);

                    // 获取id
                    Field o = Arrays.stream(fields).filter(f -> "id".equals(f.getName())).findFirst().get();
                    o.setAccessible(true);
                    Object id = o.get(parameter);
                    o.setAccessible(false);
                    jdbcTemplate.update("INSERT INTO `wms_base_document` (`id`, `table_name`) VALUES ('"+id+"', '" + tableName + "');");

//                    wmsBaseDocumentService.save(model);
                }

            }
        }
        return proceed;
    }

    @Override
    public Object plugin(Object target) {
        return Plugin.wrap(target, this);
    }

    @Override
    public void setProperties(Properties properties) {
        // TODO Auto-generated method stub
    }


}
